var page = 1;
var pageGMV = 1;
var current = 0;
var nb = 0;
var api2;
var countrie =[0, 12, 18];
var selectionne = new Array();
var api;
var api2;
var ville1;
var ville2;
var zoneArbre = [];
var test1;
var overlaytest2;
var tstcl = false;
var listvill = ['Dakar','Dakar','Thies','Thies','Louga','Louga','Louga','Louga','Matam','Matam','Matam','Matam','kaye','kaye','kaye','Mopti','Mopti','Bamako'];
var listvillGMV = ['Dakar','Dakar','Dakar','Dakar','Dakar','Dakar','Dakar','Dakar','Thies','Thies','Thies','Thies','Thies','Thies','Thies','Thies','Louga','Louga','Louga','Louga','Louga','Louga','Louga','Louga','Louga','Louga','Louga','Louga','Matam','Matam','Matam','Matam','Matam','Matam','Matam','Matam','Matam','Matam','kaye','kaye','kaye','kaye','kaye','kaye','kaye','kaye','kaye','kaye','kaye','kaye','Mopti','Mopti','Bamako'];
var arbrePanier = [];
var terrainPanier = [];
var prixTerrainNu = 10000;
var prixTerrainBassin = 150000;
var prixArbre = 5;
var sommeTer = 0;
var sommeArb = 0;
$(function() {
	overlaytest2 = $("#certificat1").overlay({
		onClose : function(){
		tstcl = false;
		$(".containerPlus").each(function(){
			if ($(this).mb_getState("iconized") == false)
				$(this).mb_toggle();}
	);
	}
	});

	
	overlaytest3 = $("#certificat2").overlay({
		onClose : function(){
		tstcl = false;
		$(".containerPlus").each(function(){
			if ($(this).mb_getState("iconized") == false)
				$(this).mb_toggle();}
	);
	}
	});

	test1 = $("#achat").overlay({
		onClose : function(){
		if (tstcl == false)
			$(".containerPlus").each(function(){
				if ($(this).mb_getState("iconized") == false)
					$(this).mb_toggle();}
		);

	}
	});

	$("#payer").bind("click",function (){
		openAchat();
		saveAchat("GMV");
		saveAchat("BR");
		return false;
	});


	$("#localiser").bind("click",function (){
		accessIJ(parseInt($("#localiserJ").val()), $("#localiserI").val(), "matrice");
		return false;
	});

	$("#localiserarbre").bind("click",function (){
		accessIJ(parseInt($("#localiserJarbre").val()), $("#localiserIarbre").val(), "GMV");
		return false;
	});

	$("#parcourirarbre").bind("click",function (){
		parcourirGMV();
		return false;
	});

	$("#parcourirbr").bind("click",function (){
		parcourirBR();
		return false;
	});


	$("#confirmAchat").bind("click", function(){

		$("#message3").appendTo("#achat");
		$("#message3").css({ top:100, left:100});
		mess =  "votre achat est bien pris en compte <br/>";
		if ($("#panierArbre").html() != "0"){
			mess = mess + "<a id =\"certif\" href = \"#\"  onclick = \" openCertificat() \"> voir le certificat</a><br/>";
		}
		if ($("#panierTerrain").html() != "0"){
			mess = mess + "<a id =\"propriete\" href = \"#\" onclick = \"openTitre()  \"> voir le titre de propri&eacute;t&eacute;</a><br/>";
		}
		$("#message3").html(mess);
		$("#message3").slideDown(1000);
		//$("#message3").fadeOut(10000);

	});

});
$(document).ready(function() {

	// initialize scrollable
	$("#ville1").html("<b>"+listvill[current]+"<br/></b>Br<span style = \" font-size: xx-small\">0," + (current * 36) +"</span>");
	$("#ville2").html("<b>"+listvill[(current+1)]+"<br/></b> Br<span style = \" font-size: xx-small\">0," + ((current+1)* 36 - 1) + "</span>");
	$("#ville3").html("<b>"+listvill[current]+"<br/></b>Br<span style = \" font-size: xx-small\">15," + (current * 36) +"</span>");
	$("#ville4").html("<b>"+listvill[(current+1)]+"<br/></b> Br<span style = \" font-size: xx-small\">15," + ((current+1)* 36 - 1) + "</span>");

	$("#villeGMV1").html("<b>"+listvill[current]+"<br/></b>GMV<span style = \" font-size: xx-small\">0," + (current * 36) +"</span>");
	$("#villeGMV2").html("<b>"+listvill[(current+1)]+"<br/></b> GMV<span style = \" font-size: xx-small\">0," + ((current+1)* 36 - 1) + "</span>");
	$("#villeGMV3").html("<b>"+listvill[current]+"<br/></b>GMV<span style = \" font-size: xx-small\">15," + (current * 36) +"</span>");
	$("#villeGMV4").html("<b>"+listvill[(current+1)]+"<br/></b> GMV<span style = \" font-size: xx-small\">15," + ((current+1)* 36 - 1) + "</span>");
	celluleBr(0, 15, 0, 35);
	celluleGMV(0, 15, 0, 35);


	$(".selectable").selectable({
		filter: '.cell, .cellArbreGMV, .cellbassin' ,
		selected: function(event, ui) {
		nb += 1;

		selectionne.push(ui.selected);
	},
	start: function(event, ui) { },
	stop: function(event, ui) {},
	unselected: function(event, ui) {selectionne =[];}
	});


	$(".scrollable").scrollable();

	$(".cell").tooltip({
		predelay : '1000',
		onBeforeShow: function(event, position) {
		this.getTip().appendTo("#matrice");
		return true;
	}

	});

	$(".cellArbreGMV").tooltip({
		predelay : '1000',
		onBeforeShow: function(event, position) {
		this.getTip().appendTo("#GMV");
		return true;
	}

	});




	api = $(".scrollable").data("scrollable");
	api.onBeforeSeek(function(a,target)  {
		current = target;
		$("#ville1").html("<b>"+listvill[current]+"<br/></b>Br<span style = \" font-size: xx-small\">0," + (current * 36) +"</span>");
		$("#ville2").html("<b>"+listvill[(current+1)]+"<br/></b> Br<span style = \" font-size: xx-small\">0," + ((current+1)* 36 - 1) + "</span>");
		$("#ville3").html("<b>"+listvill[current]+"<br/></b>Br<span style = \" font-size: xx-small\">15," + (current * 36) +"</span>");
		$("#ville4").html("<b>"+listvill[(current+1)]+"<br/></b> Br<span style = \" font-size: xx-small\">15," + ((current+1)* 36 - 1) + "</span>");
		newPage(this, target, page,"cell", "BR");
		celluleBr( 0, 15,current * 36, (current +1) * 36);

	});



	$(".myscrollable").scrollable();
	api2 = $(".myscrollable").data("scrollable");
	api2.onBeforeSeek(function(a,target)  {
		current = target;
		$("#villeGMV1").html("<b>"+listvill[current]+"<br/></b>GMV<span style = \" font-size: xx-small\">0," + (current * 36) +"</span>");
		$("#villeGMV2").html("<b>"+listvill[(current+1)]+"<br/></b> GMV<span style = \" font-size: xx-small\">0," + ((current+1)* 36 - 1) + "</span>");
		$("#villeGMV3").html("<b>"+listvill[current]+"<br/></b>GMV<span style = \" font-size: xx-small\">15," + (current * 36) +"</span>");
		$("#villeGMV4").html("<b>"+listvill[(current+1)]+"<br/></b> GMV<span style = \" font-size: xx-small\">15," + ((current+1)* 36 - 1) + "</span>");
		newPageGMV(this, target, pageGMV, "cellArbreGMV", "GMV");
		celluleGMV( 0, 15,current * 36, (current +1) * 36);

	});
	newPage(api, page, page,"cell", "BR");
	

	newPageGMV(api2, pageGMV, pageGMV, "cellArbreGMV", "GMV");
	

	$("#GMV .items").contextMenu({
		menu: 'myMenuGMV'
	},
	function(action, el, pos) {


		if (action == "eau")
			Save("eau", "GMV" );
		if (action == "case")
			Save("village", "GMV" );
		if (action == "ville")
			Save("ville", "GMV" );
		if (action == "edit")
			ajoutPanierArbre();
		if (action == "voir")
			voirArbre();

	});


	$("#matrice .items").contextMenu({
		menu: 'myMenuBR'
	},
	function(action, el, pos) {

		if (action == "edit")
			ajoutPanier();
		if (action == "bassin")
			Save("bassin", "BR" );
		if (action == "sansBassin")
			Save("sansBassin", "BR" );
		if (action == "eau")
			Save("eau", "BR" );
		if (action == "case")
			Save("village", "BR");
		if (action == "ville")
			Save("ville", "BR");
		if (action == "voir")
			voirTerrain();


	});


});

function newPage(api, target, myindice, classe, matrice){


	if (myindice >= 19){
		pays = "Niger";
	}
	else
		if (myindice >= 13){
			pays = "Mali";
		}
		else
			pays = "S&eacute;n&eacute;gal";
	region = listvill[myindice];
	if (target > api.getIndex()){
		var out = '<div id = "select'+page+'" class = "selectable">';
		var indice = myindice * 36; 
		for  ( i = 0; i<= 15; i++){
			for (j = indice; j <= (indice + 35); j++){
				out += '<div class ="'+classe+'" i = "'+i+'" j = "'+j+'"> </div>';
				out += '<div class = "tooltip" id="' + matrice + i +'_' + j + '"><b>' + matrice + ' <span style = "font-size : x-small">' + i +',' + j + ' </span></b><br/><br/>Pays : ' + pays + '<br/>R&eacute;gion : '+region+'<br/>Disponible : OUI</div>'
			}
			out += '<br/>';

		}
		out+= '</div>';


		api.addItem($("#newItem div").clone().html(out));

		$("#select"+page).selectable({ 
			filter: '.'+classe,
			selected: function(event, ui) {
			nb += 1;

			selectionne.push(ui.selected);
		},
		start: function(event, ui) {selectionne =[]; },
		stop: function(event, ui) {}
		});

		$("#select"+page+" .cell").tooltip({predelay : '1000',
			onBeforeShow: function(event, position) {
			this.getTip().appendTo("#matrice");
			return true;
		}

		});
		page +=1;


	}
}

function newPageGMV(api, target, myindice, classe, matrice){


	pays = "S&eacute;n&eacute;gal";

	region = listvillGMV[myindice];
	if (target > api.getIndex()){

		var out = '<div id = "selectGMV' + pageGMV + '" class = "selectable">';
		var indice = myindice * 36; 
		for  ( i = 0; i<= 15; i++){
			for (j = indice; j <= (indice + 35); j++){
				out += '<div class ="'+classe+'" i = "'+i+'" j = "'+j+'"> </div>';
				out += '<div class = "tooltip" id="' + matrice + i +'_' + j + '"><b>' + matrice + ' <span style = "font-size : x-small">' + i +',' + j + ' </span></b><br/><br/>Pays : ' + pays + '<br/>R&eacute;gion : '+region+'<br/>Disponible : OUI</div>'
			}
			out += '<br/>';
		}
		out += '</div>';


		api.addItem($("#newItem div").clone().html(out));

		$("#selectGMV"+pageGMV).selectable({ 
			filter: '.'+classe,
			selected: function(event, ui) {
			nb += 1;

			selectionne.push(ui.selected);
		},
		start: function(event, ui) {selectionne =[]; },
		stop: function(event, ui) {}
		});

		$("#selectGMV"+pageGMV+" .cellArbreGMV").tooltip({predelay : '1000',
			onBeforeShow: function(event, position) {
			this.getTip().appendTo("#GMV");
			return true;
		}

		});
		pageGMV +=1;


	}
}

function seekToCountrie(indice){

	for (k = page; k< indice; k++){
		newPage(api, page, page, "cell", "BR");
	}
	if (page < indice)
		page = indice;
	api.seekTo (indice-1, 2000);

}

function seekTopage(indice){

	for (k = pageGMV; k< indice; k++){
		newPageGMV(api2, pageGMV, pageGMV, "cellArbreGMV", "GMV");
	}
	if (page < indice)
		pageGMV = indice;
	api2.seekTo (indice-1, 2000);

}

function ajoutPanier(){
	var a = parseInt($("#panierTerrain").html());
	$("#panierTerrain").html(a + nb);
	a = parseInt($("#panierTerrain").html());
	$("#spanterrainachat").html(a);
	$("#nbreTerrain").html(a);
	var elmt;
	if (nb > 1){
		a =$("#zoneTerrain").html() + " BR["+$(selectionne[0]).attr("i")+"," +$(selectionne[0]).attr("j")+"]["+$(selectionne[nb-1]).attr("i")+"," +$(selectionne[nb-1]).attr("j")+"];";
		$("#zoneTerrain").html(a);

	}
	else
		if (nb == 1){
			a =$("#terrains").html() + " BR["+$(selectionne[0]).attr("i")+"," +$(selectionne[0]).attr("j")+"];";
			$("#terrains").html(a);
		}
	for (i = 0; i<nb; i++){
		elmt = selectionne.pop();
		terrainPanier.push(elmt);
		if ($(elmt).is(".cellbassin")){
			sommeTer = sommeTer + prixTerrainBassin;
		}
		else
			sommeTer = sommeTer + prixTerrainNu ;

		$(elmt).addClass("cellpanier").removeClass("cell").removeClass("selectable ui-selected");
	}
	$("#prixTerrain").html(sommeTer);
	$("#montantTerrains").html(sommeTer);

	nb = 0;
}

function ajoutPanierArbre(){
	var a = parseInt($("#panierArbre").html());
	$("#panierArbre").html(a + nb);
	a = parseInt($("#panierArbre").html());
	$("#spanarbreachat").html(a);
	$("#nbreArbre").html(a);
	var elmt;
	if (nb > 1){
		a =$("#zoneArbre").html() + " GMV["+$(selectionne[0]).attr("i")+"," +$(selectionne[0]).attr("j")+"]["+$(selectionne[nb-1]).attr("i")+"," +$(selectionne[nb-1]).attr("j")+"];";
		$("#zoneArbre").html(a);
	}
	else
		if (nb == 1){
			a =$("#arbres").html() + " GMV["+$(selectionne[0]).attr("i")+"," +$(selectionne[0]).attr("j")+"];";
			$("#arbres").html(a);
		}

	for (i = 0; i<nb; i++){
		elmt = selectionne.pop();
		arbrePanier.push(elmt);
		sommeArb = sommeArb + prixArbre;
		$(elmt).addClass("cellpanier").removeClass("cellArbreGMV").removeClass("selectable ui-selected");
	}
	$("#prixArbre").html(sommeArb);
	$("#montantarbre").html(sommeArb);
	nb = 0;
}


function Save(type, matrice){

	var elmt;
	var classe = '';
	var action = '';
	var classMatrice = '';

	switch (matrice) {
	case "BR": action = baseURL + '/matricebr/add/'; classMatrice = 'cell'; break;
	case "GMV" : action = baseURL + '/matricegmv/add/'; classMatrice = 'cellArbreGMV'; break;
	}

	switch (type) {
	case "eau": classe = "cellWaterGMV"; type = 'eau'; break;
	case "village" : classe = "cellvillageGMV"; type = 'village'; break;
	case "ville" : classe = "cellVille"; type = 'ville'; break;
	case "bassin" : classe = "cellbassin"; type = 'bassin'; break;
	case "sansBassin" : classe = "cell"; classMatrice = "cellbassin"; break;
	}
	for (i = 0; i<nb; i++){
		elmt = selectionne.pop();
		i = $(elmt).attr("i");
		j = $(elmt).attr("j");
		$(elmt).addClass(classe).removeClass(classMatrice).removeClass("selectable ui-selected");
		$.ajax({
			url: action ,
			data : {i : i, type :type,  j :j },
			datatype: "json",				        
			type: "POST",
			error: function(msg){ alert( "Error !: " + msg );},	   				        
			success:
				function(response){ 



			}
		});	
	}
	nb = 0;
}

function openOverlay(i,j) {

	var test = $("#overlaya").overlay();
	var out = "Arbre[" + i + "-" + j + "]";
	out = out + "<br/>";
	out = out + " <button type=\"button\"   onClick=\"addArbre()\" > Acheter</button> " ;
	$("#contenuAchat").html(out);
	test.load();		
}
function openAchat() {


	test1.data("overlay").load();	
	$(".containerPlus").each(function(){
		if ($(this).mb_getState("iconized") == false)
			$(this).mb_toggle();}
	);

}


function openCertificat() {

	testcl = true; overlaytest2.data('overlay').load();

	$(".containerPlus").each(function(){
		if ($(this).mb_getState("iconized") == false)
			$(this).mb_toggle();}
	);

}

function openTitre() {

	testcl = true; overlaytest3.data('overlay').load();

	$(".containerPlus").each(function(){
		if ($(this).mb_getState("iconized") == false)
			$(this).mb_toggle();}
	);
}



function addArbre(){
	var i = $("#nbarbre").attr("nb");
	var val = Number(i)+ 1;
	$("#nbarbre").html(val);
	$("#nbarbre").attr("nb",val);

}

function celluleBr (imin,imax,jmin,jmax){

	$.getJSON(
			baseURL + "/matricebr/getcoordonnee/imin/"+imin+"/imax/"+imax+"/jmin/"+jmin+"/jmax/"+jmax,
			function(json) {
				point = json.rows;
				for (i=0; i<point.length; i++) {
					a = point[i].i;
					j = point[i].j;
					proprietaire = point[i].prenom + " " + point[i].nom;
					type = point[i].type;
					classe = '';
					pays = '';
					myindice = Math.floor (j / 36);
					region = listvill[myindice];
					if (myindice >= 19){
						pays = "Niger";
					}
					else
						if (myindice >= 13){
							pays = "Mali";
						}
						else
							pays = "S&eacute;n&eacute;gal";
					switch (type) {
					case "eau": classe = "cellWaterGMV";  break;
					case "village" : classe = "cellvillageGMV"; break;
					case "ville" : classe = "cellVille"; break;
					case "bassin" : classe = "cellbassin";  break;
					case "achete" : classe = "cellAchet";  break;
					case "sansBassin" : classe = "cell";break;
					}
					$("#matrice div[i ="+ a +"][j =" + j + "]").addClass(classe).removeClass("cell").removeClass("cellAbassin");
					if (type){
						if (type == 'achete')
							$("#BR" + a + "_" + j).html('<b>BR</b> <span style = "font-size : x-small">' + a +',' + j + ' </span></b><br/>De : '+ proprietaire + '<br/>Pays : '+ pays +'<br/>R&eacute;gion : '+ region);
						else
							$("#BR" + a + "_" + j).html('<b>BR</b> <span style = "font-size : x-small">' + a +',' + j + ' </span></b><br/><br/>type : '+ type + '<br/>Pays : '+ pays +'<br/>R&eacute;gion : '+ region);

					}


				}
			}, 'json');


}


function celluleGMV (imin,imax,jmin,jmax){
	$.getJSON(
			baseURL + "/matricegmv/getcoordonnee/imin/"+imin+"/imax/"+imax+"/jmin/"+jmin+"/jmax/"+jmax,
			function(json) {
				point = json.rows;
				for (i=0; i<point.length; i++) {
					a = point[i].i;
					j = point[i].j;
					type = point[i].type;
					latitude = point[i].latitude;
					longitude = point[i].longitude;

					classe = '';
					switch (type) {
					case "eau": classe = "cellWaterGMV";  break;
					case "village" : classe = "cellvillageGMV"; break;
					case "ville" : classe = "cellVille"; break;
					
					case "achete" : classe = "cellAchet";break;
					}
					$("#GMV div[i ="+ a+"][j =" +j+"]").addClass(classe).removeClass("cellArbreGMV");
					$("#GMV"+ a + "_" + j).html('<b>GMV</b> <span style = "font-size : x-small">' + a +',' + j + ' </span></b><br/><br/>type : '+ type + '<br/>Lat : '+ latitude +'<br/>long : '+ longitude);
				}
			}, 'json');
}



function voirArbre(){
	localiserArbre($(selectionne[0]).attr("i"), 2);
	/*$(".containerPlus").each(function(){
		if ($(this).mb_getState("iconized") == false)
			$(this).mb_toggle();}
);*/
}

function voirTerrain(){
	localiserTerrain($(selectionne[0]).attr("i"), 3);
	/*$(".containerPlus").each(function(){
		if ($(this).mb_getState("iconized") == false)
			$(this).mb_toggle();}
);*/
}




function accessIJ(i,j, matrice){
	classe = '';
	if (matrice == "matrice"){
		seekToCountrie(Math.floor(i/36) + 1);
		classe = "BR";
	}
	else{
		seekTopage (Math.floor(i/36) + 1);
		classe = "GMV";
	}
	$("#"+ matrice +" div[i ="+ j +"][j =" + i + "]").addClass("cellWater").removeClass("cell cellArbreGMV");
	$("#message2").appendTo("#"+matrice);
	$("#message2").css({ top:100, left:500});
	$("#message2").html($("#"+ classe + j + "_" + i).html());
	$("#message2").slideDown(2000); $("#message2").fadeOut(10000);
}


function parcourirGMV() {
	$.getJSON(
			baseURL + "/admin/proprietaire/getgmv/id/1",
			function(json) {
				var point = json.rows;
				var etat = "nonaffich";
				var i = 0;
				var j = 0;
				$.timer(500, function (timer) {
					if (i < point.length) {
						if (etat == "nonaffich"){
							a = point[i].i;
							j = point[i].j;
							latitude = point[i].latitude;
							longitude = point[i].longitude;
							proprietaire = point[i].prenom + " " + point[i].nom;
							seekTopage (Math.floor(j/36) + 1);
							classe = "GMV";
							$("#GMV div[i ="+ a +"][j =" + j + "]").addClass("cellWater").removeClass("cell cellArbreGMV");
							$("#message2").appendTo("#GMV");
							$("#message2").css({ top:100, left:500});
							$("#message2").html('<b>GMV</b> <span style = "font-size : x-small">' + a +',' + j + ' </span></b><br/><br/>De : Me Adoulaye Wade<br/>Lat : '+ latitude +'<br/>long : '+ longitude);
							$("#message2").slideDown(1000);
							etat = "afficher";

							timer.reset(6000);
						}
						else {
							$("#message2").fadeOut(2000);
							i++;
							etat = "nonaffich";
							timer.reset(2000);
						}


					}
					else {
						timer.stop();
					}
				});
			}, 'json');


}

function parcourirBR() {
	$.getJSON(
			baseURL + "/admin/proprietaire/getbr/id/1",
			function(json) {
				var point = json.rows;
				var etat = "nonaffich";
				var i = 0;
				var a = 0;
				var b = 0;
				$.timer(500, function (timer) {
					if (i < point.length) {
						if (etat == "nonaffich"){
							a = point[i].i;
							b = point[i].j;
							proprietaire = point[i].prenom + " " + point[i].nom;
							seekToCountrie (Math.floor(b/36) + 1);
							classe = '';
							pays = '';
							myindice = Math.floor (b / 36);
							region = listvill[myindice];
							if (myindice >= 19){
								pays = "Niger";
							}
							else
								if (myindice >= 13){
									pays = "Mali";
								}
								else
									pays = "S&eacute;n&eacute;gal";
							classe = "BR";
							$("#BR div[i ="+ a +"][j =" + b + "]").addClass("cellWater").removeClass("cell cellArbreGMV");
							$("#message2").appendTo("#matrice");
							$("#message2").css({ top:100, left:500});
							$("#message2").html('<b>BR</b> <span style = "font-size : x-small">' + a +',' + b + ' </span></b><br/><br/>De : Me Abdoulaye Wade<br/>Pays : '+ pays +'<br/>R&eacute;gion : '+ region);
							$("#message2").slideDown(1000);
							etat = "afficher";

							timer.reset(6000);
						}
						else {
							$("#message2").fadeOut(2000);
							i++;
							etat = "nonaffich";
							timer.reset(2000);
						}


					}
					else {
						timer.stop();
					}
				});
			}, 'json');


}


function saveAchat(matrice){
	switch (matrice) {
	case "BR": action = baseURL + '/matricebr/add/'; classMatrice = 'cell'; id = "matrice"; break;
	case "GMV" : action = baseURL + '/matricegmv/add/'; classMatrice = 'cellArbreGMV'; id = "GMV"; break;
	}
	$("#" + id + " .cellpanier").each(function(){
		i = $(this).attr("i");
		j = $(this).attr("j");
		
		$(this).addClass("cellAchet").removeClass(classMatrice).removeClass("cellpanier");
		$.ajax({
			url: action ,
			data : {i : i, type :"achete",  j :j, proprietaire : '1' },
			datatype: "json",				        
			type: "POST",
			error: function(msg){ alert( "Error !: " + msg );},	   				        
			success:
				function(response){ 



			}
		});	
	});

}




